package com.hey.baseapplication.utils;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.hey.baseapplication.bean.User;

import java.lang.reflect.Field;

import rx.Observable;
import rx.functions.Action1;

/**
 * SharedPreference Util
 * Created by Hey on 16/12/19.
 */

public enum  SPUtil {
    instance;
    private final static String CONFIG="config";

    public  void saveUser(final Context context, User user){
        //异步储存用户信息
        Observable.just(user).subscribe(new Action1<User>() {
            @Override
            public void call(User user) {
                SharedPreferences sharedPreferences=context.getSharedPreferences(CONFIG,Context.MODE_PRIVATE);
                SharedPreferences.Editor editor= sharedPreferences.edit();
                Field names[]=user.getClass().getDeclaredFields();
                for (Field name:names){
                    try {
                        String str=name.getName();
                        if (str.equals("$change")){
                            break;
                        }
                        name.setAccessible(true);
                        String value=name.get(user).toString();
                        editor.putString(str,value);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
                editor.commit();
            }
        });
    }

    public void getUser(Context context){
        SharedPreferences sharedPreferences=context.getSharedPreferences(CONFIG,Context.MODE_PRIVATE);
        String nickname=  sharedPreferences.getString("nickname","");
        String avatar= sharedPreferences.getString("avatar" ,"");
        String basic= sharedPreferences.getString("basic_certificate","");
    }

    public void loginSuccess(Context context){
        SharedPreferences sharedPreferences=context.getSharedPreferences(CONFIG,Context.MODE_PRIVATE);
        SharedPreferences.Editor editor= sharedPreferences.edit();
        editor.putString("isLogin","true");
        editor.commit();
    }

    public boolean getLogin(Context context){
        SharedPreferences sharedPreferences=context.getSharedPreferences(CONFIG,Context.MODE_PRIVATE);
        return Boolean.parseBoolean(sharedPreferences.getString("isLogin","false"));
    }
}
